package com.bafa.front.postlogon;

import com.bafa.dbcache.LeagueCache;
import com.bafa.email.Email;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.bafa.exceptions.ErrorException;
import com.bafa.front.utils.FrontUtils;
import com.bafa.objects.Message;
import com.bafa.objects.PageBean;
import com.bafa.objects.team.Team;
import com.bafa.objects.User;
import com.bafa.services.RetrieveServices;
import com.bafa.services.ReportServices;
import com.bafa.services.results.ResultServices;

public class AddResultServlet extends PostLogonServlet {

	
	@Override
	public void doPostLogonEvent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			ErrorException {

		message = new Message();
		try {
			User user = FrontUtils.getUser(request);
			int teamAId = new Integer(request.getParameter("teamAId"))
					.intValue();
			int teamBId = new Integer(request.getParameter("teamBId"))
					.intValue();
			int teamId = new Integer(request.getParameter("teamId")).intValue();
			int goalsA = new Integer(request.getParameter("goalsA")).intValue();
			int goalsB = new Integer(request.getParameter("goalsB")).intValue();
			int matchId = new Integer(request.getParameter("matchId"))
					.intValue();
			String userId = user.getUserId();
			int divisionId = new Integer(request.getParameter("divisionId"))
					.intValue();
			ArrayList scorers = new ArrayList();
			ArrayList goals = new ArrayList();

			//int i = 1;
			String addreport = request.getParameter("addreport");
			Enumeration enumeration = request.getParameterNames();

			int goalsScored = 0;
			while (enumeration.hasMoreElements()) {
				String param = (String) enumeration.nextElement();

				if (param.indexOf("scorer") > -1) {
					String scorerName = request.getParameter(param);
					scorers.add(scorerName);
				} else if (param.indexOf("scoredgoals") > -1) {
					String scorerGoal = request.getParameter(param);
					goalsScored = goalsScored
							+ new Integer(scorerGoal).intValue();
					goals.add(scorerGoal);
				}

			}
			Team ATeam = RetrieveServices.getTeam("" + teamAId);
			Team BTeam = RetrieveServices.getTeam("" + teamBId);
			if (teamAId == teamId) {

				if (goalsA < goalsScored) {
					message
							.addMessage("Your scorers goals and your team goals do not match. Please correct");
					PageBean pageBeanTemp = (PageBean) LeagueCache.getPages()
							.get("addresult");
					pageBean = new PageBean(pageBeanTemp);
					String pageHeader = pageBean.getPageheader().replaceAll(
							"<>", "Error in your input");
					pageBean.setPageheader(pageHeader);
					return;
				}
			} else if (teamBId == teamId) {

				if (goalsB < goalsScored) {
					message
							.addMessage("Your scorers goals and your team goals do not match. Please correct");
					PageBean pageBeanTemp = RetrieveServices.getPage("addresult");
					pageBean = new PageBean(pageBeanTemp);
					String pageHeader = pageBean.getPageheader().replaceAll(
							"<>", "Error in your input");
					pageBean.setPageheader(pageHeader);
					return;
				}
			}

			String[] scorerNames = (String[]) scorers
					.toArray(new String[scorers.size()]);

			String[] scorerGoals = (String[]) goals.toArray(new String[goals
					.size()]);

			message = ResultServices.addResult(matchId, goalsA, goalsB,
					scorerNames, scorerGoals, teamId, userId, divisionId);

			if (addreport != null) {
				ReportServices.addMatchReport(request.getParameter("author"),
						request.getParameter("report"), request
								.getParameter("title"), request
								.getParameter("category"), new Integer(request
								.getParameter("matchId")), new Integer(request
								.getParameter("teamId")), new Integer(request
								.getParameter("seasonId")));
			}
			Team team1 = RetrieveServices.getTeam("" + teamId);
			StringBuffer body = new StringBuffer();
			body
					.append("This email is to confirm your input of the result between ");
			body.append(ATeam.getName());
			body.append(" and ");
			body.append(BTeam.getName() + "\n");
			body.append(ATeam.getName());
			body.append(" " + goalsA);
			body.append(" - " + goalsB);
			body.append(" " + BTeam.getName());

			String[] emails = { team1.getPrimaryContactEmail(),
					team1.getSecondaryContactEmail() };

			Email.sendEmail("bafa.bafa@ba.com", emails,
					"Confirmation of result input", body.toString());

			request.setAttribute("MESSAGES", message);

		} catch (NumberFormatException num) {
			message.addError("Please enter a valid score");
		}

	}
}
